package com.demo.javase.day73;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * @Author bug菌
 * @Date 2023-11-06 16:39
 */
public class ReferenceTypeTest {

    public static void main(String[] args) throws InterruptedException {
        testStrongReference();
        testSoftReference();
        testWeakReference();
    }

    private static void testStrongReference() {
        Object obj = new Object();
        System.out.println("Strong reference: " + obj);
        obj = null;
        System.gc();
        System.out.println("After gc, Strong reference: " + obj);
    }

    private static void testSoftReference() {
        SoftReference<Object> obj = new SoftReference<>(new Object());
        System.out.println("Soft reference: " + obj.get());
        System.gc();
        System.out.println("After gc, Soft reference: " + obj.get());
    }

    private static void testWeakReference() throws InterruptedException {
        WeakReference<Object> obj = new WeakReference<>(new Object());
        System.out.println("Weak reference: " + obj.get());
        System.gc();
        System.out.println("After gc, Weak reference: " + obj.get());

        Thread.sleep(1000);
        System.out.println("After 1s, Weak reference: " + obj.get());
    }

}
